package com.ship.gateway.inteceptor;

import com.alibaba.fastjson.JSON;
import com.banboocloud.Codec.Sm3Signature;
import com.banboocloud.Codec.Sm4Cipher;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author tangshixuan
 * @date 2023-9-14
 */
public class EncryptTest {
    public static void main(String[] args) {

        Map<String,Object> reqmap = new HashMap<>();
        reqmap.put("bimRemoteUser","lngyscbdd_uat");
        reqmap.put("bimRemotePwd","X8@3m#D7b6P9s!2R");
        reqmap.put("bimRequestId","22928d12ec8a4c1bb75283b8df71308d");
        reqmap.put("bimUid", "qWHqR1RI3TjiRg8s");
        reqmap.put("username", "ex_dingyi3");
        reqmap.put("__ENABLE__",false);
        reqmap.put("signature","3caf83e440257a1a5f26898b28601121be4f2d646fb1797fdfa9e75c42f778f9");

        Sm3Signature signature = new Sm3Signature();
        String sign2 = signature.signature(getParamStr(reqmap));
        System.out.println("签名结果2：" + sign2);
        //sm4加解密
//        String key = "JLB6L6MJVIT5Z7IL";
        String key = "X2!k4@L7#q9M6p8R";
        Sm4Cipher sm4Cipher = new Sm4Cipher();
        reqmap.put("signature",sign2);
        String target2 = sm4Cipher.encrypt(JSON.toJSONString(reqmap), key);
        System.out.println("加密报文2:" + target2);
    }

    private static String getParamStr(Map<String, Object> reqmap){
        Map<String, Object> verifymap = new TreeMap<String, Object>();
        StringBuffer sb = new StringBuffer();
        Iterator<String> it = reqmap.keySet().iterator();
        while (it.hasNext()) {
            String key = (String) it.next();
            verifymap.put(key, reqmap.get(key));
        }
        Iterator<String> ittree = verifymap.keySet().iterator();
        while (ittree.hasNext()) {
            String key = (String) ittree.next();
            if (!"signature".equals(key)) {
                sb.append(key).append("=").append(verifymap.get(key)).append("&");
            }
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }
}
